<!--vue模板-->
<template>
  <el-dialog
    v-model="visible"
    title="修改密码"
    width="25%"
    :close-on-click-modal="false"
    @close="cls"
  >
    <el-form label-width="100px" :rules="rules" :model="user" ref="modform">
      <el-form-item label="旧密码" prop="oldpwd">
        <el-input type="password" v-model="user.oldpwd"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newpwd">
        <el-input type="password" v-model="user.newpwd"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmpwd">
        <el-input type="password" v-model="user.confirmpwd"></el-input>
      </el-form-item>
    </el-form>

    <div style="text-align: center">
      <el-button type="primary" @click="modify">修改</el-button>
      <el-button @click="cls">取消</el-button>
    </div>
  </el-dialog>
</template>

<!--vue 组件选项定义-->
<script>
export default {
  data() {
    return {
      user: {
        id:"",
        oldpwd: "",
        newpwd: "",
        confirmpwd: "",
      },
      //表单验证规则
      rules: {
        oldpwd: [{ required: true, message: "请输入旧密码", trigger: "blur" }],
        newpwd: [
          { required: true, message: "请输入新密码", trigger: "blur" },
          { min: 6, max: 18, message: "密码至少6~18位", trigger: "blur" },
        ],
        confirmpwd: [
          {
            required: true,
            trigger: "blur",
            validator: (rule, value, callback) => {
              if (value == "") {
                return new Error("确认密码不能为空！");
              } else {
                //判断两次密码是否一致
                if (value != this.user.newpwd) {
                  return new Error("两次密码输入不一致！");
                }
              }

               callback();
            },
          },
        ],
      },
    };
  },

  //声明事件
  emits: ["update:visible"],

  //属性
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
  },

  //方法
  methods: {
    modify() {
  this.$refs.modform.validate(valid=>{
          if(!valid)
            return;  //验证未通过 不提交
            //获取当前登录用户
            this.user.id=this.$session.getUser().id;
         this.$http.post("/api/user/modifypwd",this.user)
         .then(res=>{
              if(res.code==200){
                  this.$message.success("修改成功");
                  //关闭
                  this.cls();
                  //清除登录信息
                  this.$session.logout();
                  //跳回登录页面
                  this.$router.push("/");
              }
         })
    });


    },
    //关闭
    cls() {
      //触发自定义事件 给父组件传值
      this.$emit("update:visible", false);
    },
  },
};
</script>

<!--vue样式 scoped当前样式只适用于当前组件-->
<style scoped></style>
